<?php
/**
 * YDatabaseQueue.php
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @since 2.0
 */

Yii::import('common.components.queue.YQueueInterface');

/**
 * Class DatabaseQueue
 */
class YDatabaseQueue implements YQueueInterface
{
	protected $name;

	protected $db;

	public function __construct($name, CDbConnection $db)
	{
		$this->name = $name;
		$this->db = $db;
	}

	/**
	 * @param $data
	 * @return mixed
	 */
	public function createItem($data)
	{
		$result = $this->db->createCommand()->insert('{{queue}}', array(
			'name' => $this->name,
			'data' => serialize($data),
		));

		return $result ? $this->db->getLastInsertID() : $result;
	}

	/**
	 * @return integer
	 */
	public function numberOfItems()
	{
		return (int)$this->db->createCommand()
			->select('COUNT(item_id)')
			->from('{{queue}}')
			->where('name=:name', array(':name' => $this->name))
			->queryScalar();
	}

	/**
	 * @param integer $leaseTime
	 * @return mixed
	 */
	public function claimItem($leaseTime = 3600)
	{
		while (true) {
			$item = $this->db->createCommand()
				->select('data, created, item_id')
				->from('{{queue}}')
				->where('expire=0 AND name=:name', array(':name' => $this->name))
				->order('created ASC')
				->limit(1, 0)
				->queryRow();
			if ($item) {
				$result = $this->db->createCommand()->update('{{queue}}', array(
					'expire' => time() + $leaseTime,
				), 'item_id=:item_id AND expire=0', array(':item_id' => $item['item_id']));
				if ($result) {
					$item['data'] = unserialize($item['data']);
					return (object)$item;
				}
			} else {
				return false;
			}
		}
	}

	/**
	 * @param $item
	 */
	public function deleteItem($item)
	{
		$this->db->createCommand()->delete('{{queue}}', 'item_id=:item_id', array(':item_id' => $item->item_id));
	}

	/**
	 * @param $item
	 * @return bool
	 */
	public function releaseItem($item)
	{
		return $this->db->createCommand()->update('{{queue}}', array(
			'expire' => 0
		), 'item_id=:item_id', array(':item_id' => $item->item_id));
	}

	/**
	 */
	public function createQueue()
	{
	}

	/**
	 * 删除队列
	 */
	public function deleteQueue()
	{
		$this->db->createCommand()->delete('{{queue}}', 'name=:name', array(':name' => $this->name));
	}
}